/**
 * Created with JetBrains WebStorm.
 * User: Eric
 * Date: 18/03/13
 * Time: 19:34
 * To change this template use File | Settings | File Templates.
 */

var util = require('util');
var objDumper = require('../Util/Dumper.js');
var World = require('../WorldModel/World.js');
var ClientWorld = require('../WorldModel/ClientWorld.js');
var basicEvent = require('./BasicEvent.js');

var EventManager = function EventManager(sessionSockets){
    ClientWorld.prototype.__proto__ = World.prototype; // only one instance of EventManager
    EventManager.instance = this;
    this.sessionSockets = sessionSockets; /* touts les sockets */
    this.world = new World();
    this.clientWorlds = new Array();
    this.initEvents();
}
EventManager.prototype = {

    initEvents : function()
    {
        var self = this;

        this.sessionSockets.of('/game').on('connection', function(err,socket,session){
            console.log("connect");
            basicEvent.connection(err,socket,session,self);
            var clientWorld = new ClientWorld(socket,self);
            self.clientWorlds.push(clientWorld);
            clientWorld.broadcastNewUser();
            socket.on('disconnect', function () {
                console.log("disconnect");
                var index = self.clientWorlds.indexOf(clientWorld);
                clientWorld.broadcastDisconnect();
                if (clientWorld.perso != undefined){
                    console.log("perso");
                    session.user.personage = clientWorld.perso;
                    console.log(session.cookie);
                    self.world.persistPerso(clientWorld.perso);
                }
                self.clientWorlds.splice(index,1);
            });
        });

    },
    getWorld : function(){
        return this.world;
    }

}
module.exports = EventManager;